﻿using CallCenter.Common;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace CallCenter.Biz
{
    /// <summary>
    /// 通用接口
    /// </summary>
    public class CommonInterface
    {
        // 获取企业ID
        // http://192.168.1.195:8083/SvrPBX.ashx?MethodName=GetEnterpriseInfo
        public Dictionary<string, string> GetEnterpriseInfo(string url)
        {
            string requestUrl = "http://" + url + "/SvrPBX.ashx?MethodName=GetEnterpriseInfo";
            Dictionary<string, string> pdata = new Dictionary<string, string>();

            // 接口版本号
            pdata.Add("version", "1.0");

            // 字符集
            pdata.Add("charset", "UTF_8");
            // 时间戳
            pdata.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            // 请求人工号
            pdata.Add("appid", "700");

            // 傲发号，设备序列号，常以AF开头，可通过查询数据库
            pdata.Add("account", "AF90114782");

            pdata.Add("methodname", "GetEnterpriseInfo");

            var s = pdata.OrderBy(e => e.Key);
            string str = "";
            foreach (var item in s)
            {
                str += item.Key + "=" + item.Value + "&";
            }

            str += "key=zfXAhqWhoBD";

            // 数据签名
            pdata.Add("sign", EncryptHelper.Md5Encrypt(str).ToUpper());
            // str += "&" + "sign=" + EncryptHelper.Md5Encrypt(str).ToUpper();

            pdata.Remove("methodname");            // 删除 
            string requestContent = JsonConvert.SerializeObject(pdata);
            string response = HttpHelper.HttpPost(requestUrl, requestContent);
            if (!string.IsNullOrEmpty(response))
            {
                HttpResponse responseMsg = JsonConvert.DeserializeObject<HttpResponse>(response);
                if (responseMsg != null)
                {
                    // 如果成功
                    if (responseMsg.RtnCode == 0)
                    {
                        if (responseMsg.data == null)
                        {
                            return null;
                        }

                        string content = responseMsg.data.ToString();
                        content = content.Remove(0, 1);
                        content = content.Remove(content.Length - 1);
                        var temp = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
                        Dictionary<string, string> info = new Dictionary<string, string>();
                        foreach (var item in temp)
                        {
                            info.Add(item.Key, item.Value.ToString());
                        }

                        return info;
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 座席登录话路
        /// </summary>
        /// <returns>是否成功</returns>
        public bool PositionLogin(string url, string enterpriceID/*, string appId,
            string account*/)
        {
            string requestUrl = "http://" + url + "/SvrPBX.ashx?MethodName=Login";

            Dictionary<string, string> pdata = new Dictionary<string, string>();

            // 接口版本号
            pdata.Add("version", "1.0");
            // 字符集
            pdata.Add("charset", "UTF_8");
            // 时间戳
            pdata.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            // 请求人工号
            pdata.Add("appid", "700");
            // 企业 ID
            pdata.Add("enterid", enterpriceID);
            // 傲发号，设备序列号，常以AF开头，可通过查询数据库
            pdata.Add("account", "AF90114782");

            pdata.Add("methodname", "Login");
            // 坐席模式，本地：0， 漫游：1
            pdata.Add("logintype", "0");

            // 坐席状态，在线：1 ，离开：2， 离线 ：0
            pdata.Add("state", "1");

            var s = pdata.OrderBy(e => e.Key);
            string str = "";
            foreach (var item in s)
            {
                str += item.Key + "=" + item.Value + "&";
            }

            str += "key=zfXAhqWhoBD";

            // 数据签名
            pdata.Add("sign", EncryptHelper.Md5Encrypt(str).ToUpper());
            // str += "&" + "sign=" + EncryptHelper.Md5Encrypt(str).ToUpper();
            pdata.Remove("methodname");
            string requestContent = JsonConvert.SerializeObject(pdata);
            string response = HttpHelper.HttpPost(requestUrl, requestContent);
            if (!string.IsNullOrEmpty(response))
            {
                HttpResponse responseMsg = JsonConvert.DeserializeObject<HttpResponse>(response);
                if (responseMsg != null)
                {
                    // 如果成功
                    if (responseMsg.RtnCode == 0)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 座席退出话路
        /// </summary>
        /// <returns>是否成功</returns>
        public bool PositionLogout(string url, string enterpriceID)
        {
            string requestUrl = $"http://{url}/SvrPBX.ashx?MethodName=Logout";

            Dictionary<string, string> pdata = new Dictionary<string, string>();

            // 接口版本号
            pdata.Add("version", "1.0");

            // 字符集
            pdata.Add("charset", "UTF_8");
            // 时间戳
            pdata.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            // 企业 ID
            pdata.Add("enterid", enterpriceID);
            // 请求人工号
            pdata.Add("appid", "700");

            pdata.Add("methodname", "Logout");

            var s = pdata.OrderBy(e => e.Key);
            string str = "";
            foreach (var item in s)
            {
                str += item.Key + "=" + item.Value + "&";
            }

            str += "key=zfXAhqWhoBD";

            // 数据签名
            // str += "&" + "sign=" + EncryptHelper.Md5Encrypt(str).ToUpper();
            pdata.Add("sign", EncryptHelper.Md5Encrypt(str).ToUpper());
            pdata.Remove("methodname");

            string requestContent = JsonConvert.SerializeObject(pdata);
            string response = HttpHelper.HttpPost(requestUrl, requestContent);
            if (!string.IsNullOrEmpty(response))
            {
                HttpResponse responseMsg = JsonHelper.JSONDeserialize<HttpResponse>(response);
                if (responseMsg != null)
                {
                    // 如果成功
                    if (responseMsg.RtnCode == 0)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 挂机接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="enterpriceId"></param>
        /// <returns></returns>
        public bool Hangup(string url, string enterpriceID)
        {
            if(string.IsNullOrEmpty(url) || string.IsNullOrEmpty(enterpriceID))
            {
                return false;
            }

            // http://{{ServerIP}}:{{webAPIPort}}/SvrPBX.ashx?MethodName=CallControl
            string requestUrl = $"http://{url}/SvrPBX.ashx?MethodName=CallControl";
            Dictionary<string, string> pdata = new Dictionary<string, string>();

            // 接口版本号
            pdata.Add("version", "1.0");
            // 字符集
            pdata.Add("charset", "UTF_8");
            // 时间戳
            pdata.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            // 企业 ID
            pdata.Add("enterid", enterpriceID);
            // 请求人工号
            pdata.Add("appid", "700");

            pdata.Add("methodname", "CallControl");
            // 操作坐席通道号
            pdata.Add("listenerfromch", "1");
            // 控制类型，挂机固定值：5
            pdata.Add("type", "5");

            var s = pdata.OrderBy(e => e.Key);
            string str = "";
            foreach (var item in s)
            {
                str += item.Key + "=" + item.Value + "&";
            }

            str += "key=zfXAhqWhoBD";

            // 数据签名
            // str += "&" + "sign=" + EncryptHelper.Md5Encrypt(str).ToUpper();
            pdata.Add("sign", EncryptHelper.Md5Encrypt(str).ToUpper());

            pdata.Remove("methodname");
            string requestContent = JsonConvert.SerializeObject(pdata);
            string response = HttpHelper.HttpPost(requestUrl, requestContent);

            /*
             {
                 "RtnCode": 0,
                 "RtnInfo": "Successful",
                 "TotalNumber": 1,
                 "SuccessNumber": 1,
                 "FailedNumber": 0,
                 "data": [
                     {
                       "code": "200",
                       "msg": "挂断成功"
                     }
                    ]
             }
             */

            if (!string.IsNullOrEmpty(response))
            {
                HttpResponse responseMsg = JsonHelper.JSONDeserialize<HttpResponse>(response);
                if (responseMsg != null)
                {
                    // 如果成功
                    if (responseMsg.RtnCode == 0)
                    {
                        string content = responseMsg.data.ToString();
                        if(string.IsNullOrEmpty(content))
                        {
                            return false;
                        }

                        content = content.Remove(0, 1);
                        content = content.Remove(content.Length - 1);
                        var temp = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
                        Dictionary<string, string> info = new Dictionary<string, string>();
                        foreach (var item in temp)
                        {
                            info.Add(item.Key, item.Value.ToString());
                        }

                        if(info.ContainsKey("code") && info["code"] == "200")
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    }
}
